<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="租户名称">
                            <el-input v-model="queryParams.name" placeholder="请输入租户名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态">
                            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="正常" :value="0" />
                                <el-option label="暂停" :value="1" />
                                <el-option label="禁用" :value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5" class="search-buttons">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <div class="operation-buttons">
                <el-button type="primary" @click="handleCreate">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增租户
                </el-button>
                <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
            </div>
        </el-card>

        <!-- 租户配置列表 -->
        <el-card>
            <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange" border
                style="width: 100%">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column prop="id" label="租户编号" align="center" width="80" /> -->
                <el-table-column type="index" label="序号" width="55" align="center"/>

                <el-table-column prop="name" label="租户名称" align="center" />
                <el-table-column prop="contactPerson" label="联系人" align="center" />
                <el-table-column prop="contactPhone" label="联系电话" align="center" />
                <el-table-column prop="email" label="邮箱" align="center" />
                <el-table-column prop="tenantCode" label="租户标识" align="center" />
                <el-table-column prop="logoUrl" label="LOGO" align="center" width="100">
                    <template #default="{ row }">
                        <el-image v-if="row.logoUrl" :preview-teleported="true" style="width: 50px; height: 50px;"
                            :z-index="222" :src="row.logoUrl" :preview-src-list="[row.logoUrl]" fit="cover" />
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.status)">
                            {{ getStatusName(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="lastUpdateTime" label="更新时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.lastUpdateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="220">
                    <template #default="{ row }">
                        <el-button type="text" @click="handleDetail(row)">详情</el-button>
                        <el-button type="text" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="text" @click="handleDelete(row)" style="color: #F56C6C">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialog.visible" title="租户配置详情" width="50%">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="租户编号">{{ detailData.id }}</el-descriptions-item>
                <el-descriptions-item label="租户名称">{{ detailData.name }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ detailData.contactPerson }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ detailData.contactPhone }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ detailData.email }}</el-descriptions-item>
                <el-descriptions-item label="租户标识">{{ detailData.tenantCode }}</el-descriptions-item>
                <el-descriptions-item label="地址">{{ detailData.address }}</el-descriptions-item>
                <el-descriptions-item label="LOGO">
                    <el-image v-if="detailData.logoUrl" style="width: 100px; height: 100px" :src="detailData.logoUrl"
                        :preview-src-list="[detailData.logoUrl]" fit="cover" />
                </el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusTagType(detailData.status)">
                        {{ getStatusName(detailData.status) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="系统配置">
                    <pre>{{ formatJson(detailData.configJson) }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="创建人">{{ detailData.creator }}</el-descriptions-item>
                <el-descriptions-item label="更新人">{{ detailData.updater }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatTime(detailData.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatTime(detailData.lastUpdateTime) }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="formDialog.visible" :title="formDialog.title" width="50%" @closed="resetForm">
            <el-form ref="tenantForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="租户编号" prop="id" v-if="formDialog.isEdit">
                    <el-input v-model="form.id" disabled />
                </el-form-item>
                <el-form-item label="租户名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入租户名称" />
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入地址" />
                </el-form-item>
                <el-form-item label="租户标识" prop="tenantCode">
                    <el-input v-model="form.tenantCode" placeholder="请输入租户标识" />
                </el-form-item>
                <el-form-item label="LOGO" prop="logoUrl">
                    <el-input v-model="form.logoUrl" placeholder="请输入LOGO地址" />
                    <el-upload class="upload-demo" action="/api/upload" :on-success="handleUploadSuccess"
                        :show-file-list="false">
                        <el-button type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="0">正常</el-radio>
                        <el-radio :label="1">暂停</el-radio>
                        <el-radio :label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="系统配置" prop="configJson">
                    <el-input v-model="form.configJson" type="textarea" :rows="4" placeholder="请输入系统配置(JSON格式)" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="formDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
    listTenantConfig,
    getTenantConfig,
    addTenantConfig,
    updateTenantConfig,
    deleteTenantConfig
} from '@/api/sysManage/tenantsConfiguration.js'

// 数据状态
const loading = ref(false)
const tenantList = ref([])
const total = ref(0)
const selectedRows = ref([])
const tenantForm = ref(null)

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    status: ''
})

// 表单数据
const form = reactive({
    id: undefined,
    name: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    address: '',
    logoUrl: '',
    status: 0,
    configJson: '{}'
})

// 详情数据
const detailData = reactive({
    id: '',
    name: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    address: '',
    logoUrl: '',
    status: 0,
    configJson: '{}',
    creator: '',
    createTime: '',
    updater: '',
    lastUpdateTime: ''
})

// 对话框状态
const detailDialog = reactive({
    visible: false
})

const formDialog = reactive({
    visible: false,
    title: '',
    isEdit: false
})

// 表单验证规则
const rules = reactive({
    name: [
        { required: true, message: '请输入租户名称', trigger: 'blur' }
    ],
    contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' }
    ],
    contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    configJson: [
        {
            validator: (rule, value, callback) => {
                try {
                    JSON.parse(value)
                    callback()
                } catch (e) {
                    callback(new Error('请输入有效的JSON格式'))
                }
            },
            trigger: 'blur'
        }
    ]
})

// 获取状态名称
const getStatusName = (status) => {
    const statusMap = {
        0: '正常',
        1: '暂停',
        2: '禁用'
    }
    return statusMap[status] || '未知'
}

// 获取状态标签样式
const getStatusTagType = (status) => {
    const typeMap = {
        0: 'success',
        1: 'warning',
        2: 'danger'
    }
    return typeMap[status] || 'info'
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
}

// 格式化JSON
const formatJson = (json) => {
    try {
        return JSON.stringify(JSON.parse(json || '{}'), null, 2)
    } catch (e) {
        return json || '{}'
    }
}

// 获取租户列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listTenantConfig(queryParams)
        tenantList.value = res?.rows || []
        total.value = res?.total || 0
    } catch (error) {
        console.error('获取租户列表失败:', error)
        ElMessage.error('获取租户列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.name = ''
    queryParams.status = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.id)
}

// 查看详情
const handleDetail = async (row) => {
    try {
        const res = await getTenantConfig(row.id)
        Object.assign(detailData, res.data)
        detailDialog.visible = true
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 新增租户
const handleCreate = () => {
    formDialog.visible = true
    formDialog.title = '新增租户'
    formDialog.isEdit = false
}

// 编辑租户
const handleEdit = async (row) => {
    try {
        const res = await getTenantConfig(row.id)
        Object.assign(form, res.data)
        formDialog.visible = true
        formDialog.title = '编辑租户'
        formDialog.isEdit = true
    } catch (error) {
        console.error('获取租户详情失败:', error)
        ElMessage.error('获取租户详情失败')
    }
}

// 上传成功处理
const handleUploadSuccess = (response) => {
    form.logoUrl = response.data.url
    ElMessage.success('上传成功')
}

// 删除租户
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该租户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteTenantConfig(row.id)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteTenantConfig(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 重置表单
const resetForm = () => {
    if (tenantForm.value) {
        tenantForm.value.resetFields()
    }
    Object.assign(form, {
        id: undefined,
        name: '',
        contactPerson: '',
        contactPhone: '',
        email: '',
        tenantCode: '',
        address: '',
        logoUrl: '',
        status: 0,
        configJson: '{}'
    })
}

// 提交表单
const submitForm = async () => {
    try {
        await tenantForm.value.validate()

        // 处理JSON配置
        const formData = {
            ...form,
            configJson: formatJson(form.configJson)
        }

        if (formDialog.isEdit) {
            await updateTenantConfig(formData)
            ElMessage.success('修改成功')
        } else {
            await addTenantConfig(formData)
            ElMessage.success('新增成功')
        }
        formDialog.visible = false
        getList()
    } catch (error) {
        if (error && error.fields) {
            ElMessage.warning('请检查表单填写是否正确')
        } else {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    }
}

// 初始化
getList()
</script>

<style scoped>
.search-card {
    margin-bottom: 20px;
}

.search-buttons {
    text-align: right;
    padding-top: 5px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.upload-demo {
    margin-top: 10px;
}

.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}

.el-image {
    position: relative;
    z-index: 1000;
    /* 设置一个足够高的值 */
}

pre {
    background: #f4f4f4;
    padding: 10px;
    border-radius: 4px;
    max-height: 200px;
    overflow: auto;
}
</style>